﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using mmoss.classes.Interfaces;

namespace mmoss.classes
{
    public class AuthNet : IEComm
    {
        #region eComm Members

        public string PostURL{get;set;}
        public string APIkey{get;set;}
        public string Login{get;set;}
        public string Password{get;set;}
        public bool Delimited{get;set;}
        public char DelimitedChar{get;set;}
        public orm.Patient Patient{get;set;}
        public bool TestMode { get; set; }
        public string TransType { get; set; }
        public string CCNumber { get; set; }
        public string CCExpDate { get; set; }
        public string CCVNum { get; set; }
        public decimal CCAmount { get; set; }
        public string TransactionNumber { get; set; }
        public bool Success { get; set; }
        public string CCDescription { get; set; }
        public string Result { get; set; }
        public AuthNet()
        {
            //base constructor
        }
        public void Charge()
        {
            // By default, this sample code is designed to post to our test server for
            // developer accounts: https://test.authorize.net/gateway/transact.dll
            // for real accounts (even in test mode), please make sure that you are
            // posting to: https://secure.authorize.net/gateway/transact.dll
            //String post_url = "https://test.authorize.net/gateway/transact.dll";


            Dictionary<string, string> post_values = new Dictionary<string, string>();
            //the API Login ID and Transaction Key must be replaced with valid values
            post_values.Add("x_cpversion", "1.0");
            post_values.Add("x_market_type", "2"); //retail
            post_values.Add("x_device_type", "5");  //pc-based terminal
            post_values.Add("x_login", Login);
            post_values.Add("x_tran_key", APIkey);
            post_values.Add("x_delim_data", Delimited.ToString());
            post_values.Add("x_delim_char", DelimitedChar.ToString());
            post_values.Add("x_relay_response", "FALSE");
            post_values.Add("x_test", TestMode.ToString());

            post_values.Add("x_type", TransType);
            post_values.Add("x_method", "CC");
            post_values.Add("x_card_num", CCNumber);
            post_values.Add("x_exp_date", CCExpDate);

            post_values.Add("x_amount", CCAmount.ToString());
            post_values.Add("x_description", CCDescription);
            post_values.Add("x_first_name", Patient.patientFirstName);
            post_values.Add("x_last_name", Patient.patientLastName);
            post_values.Add("x_address", Patient.patientAddress);
            post_values.Add("x_state", Patient.patientState);
            post_values.Add("x_zip", Patient.patientZip);
            // Additional fields can be added here as outlined in the AIM integration
            // guide at: http://developer.authorize.net

            // This section takes the input fields and converts them to the proper format
            // for an http post.  For example: "x_login=username&x_tran_key=a1B2c3D4"
            String post_string = "";

            foreach (KeyValuePair<string, string> post_value in post_values)
            {
                post_string += post_value.Key + "=" + HttpUtility.UrlEncode(post_value.Value) + "&";
            }
            post_string = post_string.TrimEnd('&');

            // The following section provides an example of how to add line item details to
            // the post string.  Because line items may consist of multiple values with the
            // same key/name, they cannot be simply added into the above array.
            //
            // This section is commented out by default.
            /*
            string[] line_items = {
                "item1<|>golf balls<|><|>2<|>18.95<|>Y",
                "item2<|>golf bag<|>Wilson golf carry bag, red<|>1<|>39.99<|>Y",
                "item3<|>book<|>Golf for Dummies<|>1<|>21.99<|>Y"};
	
            foreach( string value in line_items )
            {
                post_string += "&x_line_item=" + HttpUtility.UrlEncode(value);
            }
            */

            // create an HttpWebRequest object to communicate with Authorize.net
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(PostURL);
            objRequest.Method = "POST";
            objRequest.ContentLength = post_string.Length;
            objRequest.ContentType = "application/x-www-form-urlencoded";

            // post data is sent as a stream
            StreamWriter myWriter = null;
            myWriter = new StreamWriter(objRequest.GetRequestStream());
            myWriter.Write(post_string);
            myWriter.Close();

            // returned values are returned as a stream, then read into a string
            String post_response;
            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
            {
                post_response = responseStream.ReadToEnd();
                responseStream.Close();
            }

            // the response string is broken into an array
            // The split character specified here must match the delimiting character specified above
            Array response_array = post_response.Split('|');

            // the results are output to the screen in the form of an html numbered list.
            Result = "";
            int iLoop = 1;
            foreach (string value in response_array)
            {
                Result += iLoop.ToString()+"==" + value + Environment.NewLine;
                iLoop++;
            }
            Result += Environment.NewLine;
            
            // individual elements of the array could be accessed to read certain response
            // fields.  For example, response_array[0] would return the Response Code,
            // response_array[2] would return the Response Reason Code.
            // for a list of response fields, please review the AIM Implementation Guide

        }
        #endregion
    }
}
